<template>
	<view class="full-width">
		<view @click.stop="handleOpenPopup">
			<u-input v-model="dictLabel" border="none" inputAlign="right" :placeholder="placeholder"
				class="full-width pointer-none" :disabled="disabled" readonly>
				<u-icon slot="suffix" name="arrow-right"></u-icon>
			</u-input>
		</view>

		<!-- <van-popup v-model="open" round position="bottom"> -->
		<u-popup :show="open" @close="handlePickerCancel">
			<van-picker show-toolbar :columns="columns" value-key="text" :default-index="currentIndex"
				@cancel="handlePickerCancel" @confirm="handlePickerConfirm" />
		</u-popup>
		<!-- </van-popup> -->
	</view>
</template>

<script>
	import {
		getDicts
	} from "@/api/system/dict";
	
	export default {

		props: {
			value: {
				type: String
			},
			disabled: {
				type: Boolean,
				default: false
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			dict: {
				type: [String, Array],
				default: undefined
			},
			readonly: {
				type: Boolean,
				default: true
			},
			first: {
				type: Boolean,
				default: true
			}

		},
		data() {
			return {
				currentIndex: undefined,
				dictLabel: '',
				open: false,
				columns: []
			}
		},
		watch: {
			value: {
				immediate: true,
				async handler(val) {
					if (val) {
						if (!this.columns.length) {
							await this.getDictsData()
						}
						let findIndex = this.columns.findIndex(item => item.value === val)
						this.dictLabel = this.columns[findIndex]['text']
						this.currentIndex = findIndex
					} else if (this.first) {
						this.handlePickerConfirm({detail:{value:this.columns[0]}})
						this.currentIndex = 0
					} else {
						this.dictLabel = undefined
						this.currentIndex = undefined
					}
				}
			},
			dict: {
				immediate: true,
				async handler(val) {
					if (val) {
						if (Array.isArray(val)) {
							this.columns = val
							if (this.value) {
								let findIndex = this.columns.findIndex(item => item.value === this.value)
								this.dictLabel = this.columns[findIndex]['text']
								this.currentIndex = findIndex
							}
						} else {
							await this.getDictsData()
						}
						if (this.first) {
							this.handlePickerConfirm({detail:{value:this.columns[0]}})
							this.currentIndex = 0
						}
					}

				}
			}
		},
		methods: {
			handleOpenPopup() {
				if(this.disabled) return
				this.open = true
			},
			async getDictsData() {
				await getDicts(this.dict).then((res) => {
					this.columns = res.data.map(item => {
						return {
							text: item.dictLabel,
							value: item.dictValue
						}
					})
				})
			},
			handlePickerCancel() {
				this.open = false
			},
			handlePickerConfirm(picker) {
				let {
					value,
					index
				} = picker.detail
				this.dictLabel = value['text']
				this.open = false
				this.$emit('input', value['value'])
			}
		}
	}
</script>

<style>

</style>